package com.xuxu.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuxu.blog.dao.PermissonDao;
import com.xuxu.blog.dao.RoleDao;
import com.xuxu.blog.dao.RolePermissionDao;
import com.xuxu.blog.dao.UserDao;
import com.xuxu.blog.entity.PermissonEntity;
import com.xuxu.blog.entity.UserEntity;
import com.xuxu.blog.service.PermissonService;
import com.xuxu.common.utils.PageUtils;
import com.xuxu.common.utils.Query;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.stream.Collectors;


@Service("permissonService")
@Slf4j
public class PermissonServiceImpl extends ServiceImpl<PermissonDao, PermissonEntity> implements PermissonService {
    @Resource
    private RoleDao roleDao;
    @Resource
    private RolePermissionDao rolePermissionDao;
    @Resource
    private PermissonDao permissonDao;
    @Resource
    private UserDao userDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PermissonEntity> page = this.page(
                new Query<PermissonEntity>().getPage(params),
                new QueryWrapper<PermissonEntity>()
        );

        return new PageUtils(page);
    }

    public HashSet<PermissonEntity> getAllPermission(UserEntity user) {
        /**
         * 方法一：通过一个个表去查询然后存储到一个集合中。很麻烦
         */
        // HashSet<PermissonEntity> permissionSet = new HashSet<>();
        // //从user_role中通过用户id查询所有的角色信息
        // RolePermissionServiceImpl rolePermissionService = new RolePermissionServiceImpl();
        // QueryWrapper<RolePermissionEntity> wrapper = new QueryWrapper<>();
        // wrapper.eq("role_id", user.getRole());
        // 获取当前用户角色的所有权限id（中间表）
        // List<RolePermissionEntity> userRoles = rolePermissionDao.selectList(wrapper);
        // log.error("用户权限有：{}",userRoles);
        // // 查询所有的权限
        // for (RolePermissionEntity userRole : userRoles) {
        //    permissionSet.add(permissonDao.selectById(userRole.getPermissionId()));
        // }
        // log.debug("实际权限有：{}", permissionSet);
        /**
         * 通过sql语句的多表连接方式进行拼接
         */
        HashSet<PermissonEntity> permissions = userDao.selectPermissions(user.getUsername());
        LinkedHashSet<PermissonEntity> sortedPermision = permissions.stream().sorted(Comparator.comparing(PermissonEntity::getId))
                .collect(Collectors.toCollection(LinkedHashSet::new));
        return sortedPermision;
    }
}